package com.lhr.common.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lhr.common.util.domain.IPAddressInfo;

public class IPAddressUtil {
	private static Logger log = LoggerFactory.getLogger(IPAddressUtil.class);
	private static final String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=java&ip=";
	private static final String splitStr = "\t";

	public static IPAddressInfo getIPAddressInfo(String ip) {
		try {
			HttpClient httpclient = new HttpClient();
			httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			PostMethod method = new PostMethod(url);

			int statusCode = httpclient.executeMethod(method);

			if (statusCode != HttpStatus.SC_OK) {
				log.error("Method failed: " + method.getStatusLine());
			}

			String responseContent = method.getResponseBodyAsString();
			return conversion(responseContent, ip);
		} catch (Exception e) {
			log.error(e.toString(), e);
			return null;
		}

	}

	private static IPAddressInfo conversion(String content,
			String ip) {
		String[] contents = content.split(splitStr);
		int ret = contents[0] == null ? -1 : Integer.valueOf(contents[0]);
		IPAddressInfo ipAddressInfo = new IPAddressInfo();
		ipAddressInfo.setIp(ip);
		ipAddressInfo.setRet(ret);
		if (ret != 1) {
			log.error("获取IP出错,IP为{}", ip);
			return ipAddressInfo;
		}
		if (contents.length >= 2)
			ipAddressInfo.setStart(contents[1]);
		if (contents.length >= 3)
			ipAddressInfo.setEnd(contents[2]);
		if (contents.length >= 4)
			ipAddressInfo.setCountry(contents[3]);
		if (contents.length >= 5)
			ipAddressInfo.setProvince(contents[4]);
		if (contents.length >= 6)
			ipAddressInfo.setCity(contents[5]);
		if (contents.length >= 7)
			ipAddressInfo.setDistrict(contents[6]);
		if (contents.length >= 8)
			ipAddressInfo.setIsp(contents[7]);
		if (contents.length >= 9)
			ipAddressInfo.setType(contents[8]);
		if (contents.length >= 10)
			ipAddressInfo.setDesc(contents[9]);
		return ipAddressInfo;
	}

}
